<!--
* description: 备件借出登记
* author: xuliwen
* createdDate: 2021-01-21
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="false"
      :is-show-pagination="false"
      :dynamic-is-show-more-btn="true"
      :dynamic-api-style="'restful'"
      :callback-obj="callbackObj"
    >

      <template #borrowQty="scope">
        <el-input
          :key="scope.col.prop"
          v-model="scope.row['borrowQty']"
          placeholder="请输入数量"
          clearable
          @change="numChange($event, scope.row, scope.col, scope.$index)"
        />
      </template>
    </one-table-template>
    <!-- 备件选择弹窗 -->
    <sparePartsSelection
      @sendCodeClose="sendCodeClose"
      @partChoosed="partChoosed"
      :popupsVisible="technicianEditVisible"
      :warehouseId="warehouseId"
      :key="technicianEditKey"
    ></sparePartsSelection>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import OneTableTemplate from "@/components/templates/oneTable";
import Vue from "vue";
import api from "@/api/pa/apiBranchWarehouse";
import request from "@/utils/request";

export default {
  name: "partsBorrowingRegister",

  components: {
    OneTableTemplate,
    sparePartsSelection: () => import("./sparePartsSelection.vue"),
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ""], function () {
      next();
    });
  },
  data() {


    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path;

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode]);

    return {
      // 回调方法对象
      callbackObj: {

        onCheckSelectChange: selection => {
          this.selectiondata = selection
        }

      },
      icon: "el-icon-arrow-down",
      status: false,
      editRowData: {},
      selectiondata: [],
      technicianEditVisible: false,
      technicianEditKey: "technicianEditKey",
      warehouseId: "",
      // 网格查询API配置对象
      apiConfig: api.partsBorrowingRegister,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey3",
          type: "",
          size: "small",
          parentFileds: "disabled:table",
          clickEvent: () => this.save(),
          text: "保存", // 新增
          name: "adopt",
          position: "right",
        },
        {
          compKey: "btnKey2",
          type: "",
          size: "small",
          name: "reset",
          clickEvent: () => this.reset(),
          text: this.$t("sys.button.reset"),
          position: "right", // 重置
        },
        // {
        //   compKey: 'btnKey3',
        //   type: '',
        //   size: 'small',
        //   name: 'add',
        //   clickEvent: this.add,
        //   text: this.$t('sys.button.add'), // 新增
        //   position: 'left'
        // },
        {
          compKey: "btnKey3",
          type: "",
          size: "small",
          parentFileds: "disabled:table",
          clickEvent: () => this.partChoose(),
          text: "备件选择", // 新增
          name: "adopt",
          position: "left",
        },
        {
          compKey: "btnKey4",
          parentFileds: "disabled:table",
          type: "",
          size: "small",
          clickEvent: () => this.deleteTable(),
          text: "备件删除", // err
          name: "reject",
          position: "left",
        },
        {
          compKey: "btnKey4",
          type: "",
          size: "small",
          clickEvent: () => this.handFileListChange(),
          text: "批量导入",
          name: "import", // 按钮图标样式
          position: "upload",
        },
        {
          compKey: "btnKey8",
          type: "text",
          size: "small",
          name: "",
          position: "upload",
          click: (event) => {
            this.templateDownload();
          },
        },
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
              .tableComponents
          : [
              {
                compKey: "compKey1",
                labelName: "仓库名称：",
                codeField: "warehouseId",
                textField: "warehouseName",
                customObj: {
                  api: api.queryWareHouse,
                  defOptionFields: ["warehouseId", "warehouseName"],
                },
                clearable: false,
                component: () => import("@/components/org/commonSelect"),
                type: "dropdownList",
                isMul: false,
                isMust: true,
                isRequire:true,
              },
              {
                compKey: "compKey2",
                labelName: "借件人员：",
                codeField: "auditorId",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
                isRequire:true,
                isword:false,
              },
              {
                compKey: "compKey3",
                labelName: "联系电话：",
                codeField: "linkPhone",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
                isRequire:true,
                validrule: {
                  noRequire: false,
                  isformat: /^((0\d{2,3}-\d{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/
                },

              },
              {
                compKey: "compKey4",
                labelName: "承诺归还日期：",
                codeField: "promisesRuturnDate",
                component: () =>
                  import("@/components/org/datePicker/datePicker.vue"),
                type: "YYYY-MM-DD",
                format: "yyyy-MM-dd",
                dateOptionsType: "0",
                isMul: false,
                isMust: true,
                isRequire:true,
              },
              {
                compKey: "compKey5",
                labelName: "借件原因：",
                codeField: "borrowReason",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
                isRequire:true,
              },
              {
                compKey: "compKey6",
                labelName: "VIN：",
                codeField: "vin",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                isMust: true,
                isRequire:true,

              },
              //  {
              //   compKey: "compKey7",
              //   labelName: "借件金额：",
              //   codeField: "maintenanceType",
              //   component: () => import("@/components/org/commonInput"),
              //   type: "inputText",
              //   isMul: false,
              //   isMust: false,
              //   disabled:true,
              // },
            ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
              {
                prop: "updateControlId",
                label: "并发控制ID",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "partId",
                label: "备件id",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "dlrId",
                label: "dlrId",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "partNo",
                label: "备件编号",
              },
              {
                prop: "partName",
                label: "备件名称",
              },

              {
                prop: "partType",
                label: "备件类别",
              },
              {
                prop: "carConfigIdList",
                label: "适用车型",
              },
              // {
              //   prop: "partAttrName",
              //   label: "备件属性",
              // },
              {
                prop: "minSalesPage",
                label: "最小销售包装",
              },
              {
                prop: "accountQty",
                label: "库存数量",
              },
              {
                prop: "actuallyAvailable",
                label: "可用库存",
              },
              {
                prop: "borrowQty",
                label: "借件数量+",
                // isComponent: true,
                isSlot: true,
                // comps: [
                //   {
                //     compKey: "compKey5" + this.$utils.generateId(),
                //     codeField: "borrowQty",
                //     component: () => import("@/components/org/commonInput"),
                //     type: "inputText",
                //   },
                // ],
              },
              {
                prop: "pointPriceTax",
                label: "借件单价",
              },
              {
                prop: "debitamount",
                label: "借件金额",
              },
            ],
      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          warehouseId: "",
          auditorId: "",
          linkPhone: "",
          promisesRuturnDate: "",
          borrowReason: "",
          vin: "",
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
    };
  },
  watch: {
    "formField.orderStatus": {
      deep: true,
      handler: function (newV, oldV) {
        console.log("watch中：", newV);
        // this.querybystatus(newV)
        this.queryTable();
      },
    },
  },
  mounted() {
    // 列表查询
    this.queryTable(1);
  },

  methods: {
    numChange(val, row, col, index) {

      const panter = /c|(^[1-9][0-9]*$)/
      if (!panter.test(val)) {
        row[col['prop']] = ''
        row['debitamount'] = '0.00'
        if (val) {
          this.$message('请输入正确的数量！')
        }
      } else if (Number(val) < Number(row['minSalesPage'])) {
        row[col['prop']] = ''
        row['debitamount'] = '0.00'
        this.$message('不能小于最小订货量！')
      } else {
        // row['debitamount'] = (Number(val) * Number(row['pointPriceTax'])).toFixed(2)
        this.$set(row, 'debitamount', (Number(val) * Number(row['pointPriceTax'])).toFixed(2))
      }
      //debitamount=borrowQty *pointPriceTax

      // this.totalType = this.$refs['multipleTable'].list.length
      // this.totalAmount = this.$refs['multipleTable'].list.reduce((amount, row) => {
      //   return Number(amount) + (Number(row['purAmount']) || 0)
      // }, 0).toFixed(2)
    },

    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file);
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: "文件大小不能超过50M",
          type: "warning",
        });
        return false;
      }
      let fileType = file.name.substr(file.name.lastIndexOf(".") + 1);
      if (fileType != "xls" && fileType != "xlsx") {
        this.$message({
          message: "只能导入后缀为xls,xlsx的文件！",
          type: "warning",
        });
        return false;
      }
      return true;
    },
     handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: "导入中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const that = this;
      const url = api.beachImport.APIUrl;
      that
        .$requestUpload(url, param)
        .then((response) => {
          loading.close();
          if (response.result === "1") {
            this.$refs['multipleTable'].list=response.rows
          } else {
            this.$message({
              message: response.msg,
              type: "warning",
            });
          }
        })
        .catch((err) => {});
    },
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime("备件借出登记.xlsx");
      this.$requestAPI({
        apiUrl: api.downloadTemplate.APIUrl,
        variables: { dataType: "excel" },
      })
        .then((res) => {
          this.$utils.downloadFile(res, fileName);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    partChoose() {
      if (
        this.formField.warehouseId == "" ||
        this.formField.warehouseId == null
      ) {
        this.$message.warning("请选择备件仓库名称");
      } else {
        this.technicianEditVisible = true;
        this.warehouseId = this.formField.warehouseId;
      }
    },
    partChoosed(parmars) {
      parmars.forEach((element) => {
        this.$refs["multipleTable"].list.push(element);
      });
    },
    // 备件选择弹窗
    sendCodeClose() {
      this.technicianEditVisible = false;
      this.technicianEditKey += "1";
    },
    save() {
      this.$utils.validataMoth(this, 'validpage')
      let parmarsData={...this.formField,paramList:this.$refs["multipleTable"].list}
      let that=this
      request({
        url: api.partsBorrowingRegisterSave.APIUrl,
        method: "post",
        data: parmarsData,
      }).then((res) => {
        if (res.result == "1") {
          that.$message.success(res.msg);
          // that.$router.go(0)
          this.reset()
          this.$refs['multipleTable'].list = []
        } else {
          that.$message.warning(res.msg);
        }
      });
    },
    deleteTable() {
      // for (let i of this.selectiondata) {
      //   this.$refs["multipleTable"].list = this.$refs[
      //     "multipleTable"
      //   ].list.filter((item) => item !== i);
      // }
      this.$confirm('确定要删除吗？').then(_ => {
        if (!this.selectiondata.length) return this.$message('请选择要删除的数据！')
        // 需要删除数据的 index 列表
        this.$refs['multipleTable'].list = this.$refs['multipleTable'].list.reduce((newList, row, idx) => {
          if (!this.selectiondata.map(o => o['partId']).includes(row['partId'])) {
            newList.push(row)
          }
          return newList
        }, [])
        // 重新加索引
        this.$refs['multipleTable'].list.forEach((row, index) => {
          row['index'] = index
        })
      })
    },
  },
};
</script>
